package com.dkm.ou.me.domain;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.dkm.base.core.helper.SpringHelper;
import com.dkm.base.core.util.string.StringUtils;
import com.dkm.biz.domain.AbstractDomain;
import com.dkm.ou.me.persistence.dao.RoleGrantDao;
import com.dkm.ou.me.persistence.dao.UserDao;
import com.dkm.ou.me.persistence.entity.ResGrantPo;
import com.dkm.ou.me.persistence.entity.RoleGrantPo;
import com.dkm.ou.me.persistence.entity.RolePo;
import com.dkm.ou.me.persistence.entity.UserPo;
import com.dkm.ou.me.repository.RoleGrantRepository;

/**
 * 对象功能:t_ou_user 领域对象实体
 * 开发公司:dkm.com
 * 开发人员:ZHH
 * 创建时间:2016-10-27 22:08:42
 */
@SuppressWarnings("serial")
@Service
@Scope("prototype")
public class User extends AbstractDomain<String, UserPo>{
	 
	 private UserDao userDao = null;
	 private RoleGrantDao roleGrantDao = null;
	 private RoleGrantRepository roleGrantRepository = null;

	protected void init(){
		userDao = SpringHelper.getBean(UserDao.class);
		roleGrantDao = SpringHelper.getBean(RoleGrantDao.class);
		roleGrantRepository = SpringHelper.getBean(RoleGrantRepository.class);
		setDao(userDao);
	}
	public void save(User user) {
		//是否新增
		boolean isNew = StringUtils.isEmpty(user.getId())?true:false;
		Map<String, String> 	resGrantMap=new HashMap<String, String>();
		UserPo userPo=user.getData();
		if(!isNew){
			/*Map<String, Object> params=new HashMap<String, Object>();
			params.put("whereSql","user_id_='"+ userPo.getId()+"'");
			params.put("userId", user.getId());
			List<RoleGrantPo> roleGrantPos=	roleGrantRepository.findAll(params);
			if(roleGrantPos!=null){
				for(RoleGrantPo roleGrantPo:roleGrantPos){
					resGrantMap.put(roleGrantPo.getRoleId(), roleGrantPo.getStatus());
				}
			}*/
			Map<String, Object> params=new HashMap<String, Object>();
			params.put("userId", user.getId());
			roleGrantDao.deleteByKey("deleteByRoleId",params);
			user.update();
		}else{
			user.create();
		}
		String roleIds=userPo.getRoleIds();
		if(roleIds!=null&&!"".equals(roleIds)){
			String[] ids=roleIds.split(";");
			for(String roleId:ids){
				RoleGrantPo roleGrantPo = new RoleGrantPo();
				roleGrantPo.setId(getIdGenerator().genSid());
				roleGrantPo.setRoleId(roleId);
				roleGrantPo.setUserId(userPo.getId());
				roleGrantPo.setCreateTime(new Date());
				roleGrantPo.setAuditTime(new Date());
				roleGrantPo.setStatus("active");
				roleGrantDao.create(roleGrantPo);
			}
		}
		
		
	}	 
}
